<?php
namespace App\Http\Controllers\Webapi;

use App\Common\ApiData;
use App\Http\Controllers\Controller;
use App\Models\V1\ChangeOrderTemplateModel;
use App\Models\V1\ChapterModel;
use App\Models\V1\CompanyModel;
use App\Models\V1\DrpModel;
use App\Models\V1\MemberModel;
use App\Models\V1\NewOrderTemplateModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Weixin\WeixinServiceController  as WeixinService;
use App\Http\Controllers\Service\Region;


class ChapterOrderController extends Controller{

    private $prisidentPercent   = 60;   //会长所占比例
    private $apiData;
    private $orderType  = "chapterOrder";
    public function __construct(){
        $this->apiData  = new ApiData();
    }

    /**
     * 添加分会订单
     * */
    public function add_order(Request $request){
        //orderType:订单类型可分为3种G
        //     clo:学习官
        //  member:会员
        // company:公司
        $orderType  = $request->input('orderType');
        $userId     = $request->input('userId');

        $orderData  = $request->input('order');
        $orderData  = \GuzzleHttp\json_decode($orderData,true);

        foreach($orderData as $key=>$v)
        {
            $orderData[$key]  = trim($v);
        }
        unset($orderData['member_name']);
        unset($orderData['member_mobile']);
        unset($orderData['discount_money']);

        $newMobile      = $orderData['new_member_mobile'];
        $newMemberName  = $orderData['new_member_name'];

        $companyCode    = $orderData['new_company_code'];
        $companyName    = $orderData['new_company_name'];


        $memberModel    = new MemberModel();
        $chapterModel   = new ChapterModel();
        $regionService  = new Region();


        switch($orderType)
        {
            case 'company':
                $checkData  = [
                    "comCode"   => [$companyCode,'缺少公司编号',3001],
                    "comName"   => [$companyName,'缺少企业名称',3002],
                    "city"      => [$orderData['city'],'请选择城市',3003],
                    "mobile"    => [$newMobile,'请填写管理员号码',3004]
                ];
                break;
            default:
                $checkData  = [
                    "name"      => [$newMemberName,"请填写姓名",3005],
                    "mobile"    => [$newMobile,'请填写手机号',3006]
                ];
                break;
        }

        $result = $this->check_params($checkData);
        if($result->status == false)
        {
            return apiData()->send($result->code,$result->message);
        }

        //***********1.检查提交的数据是否符合要求****************

        if(!preg_match('/1\d{10}/',$newMobile))
        {
            return $this->apiData->send(3001,'手机号异常');
        }


        //2.检查添加的新会员是否已经存在
        if($orderType == 'clo' || $orderType == 'member')
        {

            $memberInfo = $memberModel->get_member_info_by_mobile($newMobile);

            if($orderType == 'clo' && (!$memberInfo || $memberInfo->States == 0))
            {
                return $this->apiData->send(4007,"用户{$newMobile}还不是会员");
            }

            //2.检查订单系统是否存在未处理的订单
            $hasOrder = DB::table('chapter_order')
                ->where('new_member_mobile',$newMobile)
                ->where('is_delete',0)
                ->where('company_check_status',0)
                ->first();
            if($hasOrder)
            {
                return $this->apiData->send(4003,"号码{$newMobile}正在审核中,勿重复提交");
            }


        } elseif($orderType == 'company') { //如果是企业会员

            //检查该企业是否已经被添加过
            $companyInfo    = DB::table('chapter_order')
                                ->where('new_company_code',$companyCode)
                                ->where('is_delete',0)
                                ->where('company_check_status','<>',2)
                                ->first();

            if($companyInfo && $companyInfo->company_check_status == 0)
            {
                return $this->apiData->send(4004,'本企业正在审核中，请勿重复提交');

            } elseif($companyInfo && $companyInfo->company_check_status == 1) {

                return $this->apiData->send(4005,'本企业已存在，请勿重复提交');
            }
        }

        $cloDetail   = $memberModel->get_member_info_by_id($userId);


        /*==============================================
         ********* 3.找到本订单对应的发起人或会长 *********
         ===============================================*/

        //客户的位置
        if($orderType == 'company')
        {
            $userCity   = $orderData['city'];

        } else {//获得新用户的所属区域

            $cityInfo = $regionService->get_mobile_city_info($newMobile);
            $userCity = $cityInfo ? $cityInfo->region_id : $cloDetail->city;
        }


        //1）找到学习官所属的区域 首先检查本区域是否有会长
        $prisidentInfo  = $chapterModel->get_customer_chapter($userCity,$userId);


        $chapterId      = $prisidentInfo->chapter_id;               //订单所属分会
        $prisidentUserId= $prisidentInfo->user_id;                  //会长ID
        $cloInfo        = DB::table('chapter_drp')->where('user_id',$userId)->first();


        //******4.找到相关受益人 这些受益人应该是新会员的三个学习官用户ID******


        $drpModel       = new DrpModel();
        $parentsDrp     = $drpModel->get_parent_drp_list($userId,1);
        $incomeMember   = [$userId,$prisidentUserId];

        foreach($parentsDrp as $parent)
        {
            array_push($incomeMember,$parent->UserID);
        }

        if(count($parentsDrp) == 0)
        {
            array_push($incomeMember,system_log('mishuId'));
        }

        //无论是学习官还是会长发起的订单 首先从已有的余额中扣除 判断余额是否足够
        //1、足够，则不需要向上级返点
        //2、不够，需要向会长请求剩余的金额并返点

        $totalMoney         = $orderData['total_money'];   //总金额
        $userSurplusMoney   = $cloInfo->surplus_money;


        //*****************5.计算需要的金额***************************

        //需要从会长仓库扣除的金额
        if($orderType == 'clo')
        {
            $payMoney   = $needMoney = $totalMoney;  //推荐的为学习官  全从会长仓库购买

        } else {

            $needMoney  = $totalMoney - $userSurplusMoney;
            if($needMoney > 0)
            {
                $payMoney   = $needMoney;
            }
            else
            {
                $payMoney   = 0;
                $needMoney  = 0;
            }
        }

        $orderAddTime   = date_time();
        $orderData2 = [
            'chapter_id'    => $chapterId,
            'check_user_id' => $prisidentUserId,
            'user_id'       => $userId,
            'order_type'    => $orderType,
            'add_time'      => $orderAddTime,
            'check_status'  => 0,
            'income_member' => implode(',',$incomeMember),
            'pay_money'     => $payMoney,
            'city'          => $userCity
        ];

        //加入新订单
        $orderData  = array_merge($orderData,$orderData2);
        $orderId    = DB::table('chapter_order')->insertGetId($orderData);


        /*======扣除学习官的余额=======*/
        if($orderType != 'clo')
        {
            //1.被添加的不为学习官  减去余额
            if($needMoney > 0)
            {
                $money  = $totalMoney-$needMoney;   //不够，减去从仓库拿的，其余扣自己的

            } else {

                $money  = $totalMoney;              //足够，全部扣自己的
            }
            $chapterModel->use_officer_money($userId,$money); //2 学习官
        }


        //如果支付的金额=0 则为上级学习官自动确定订单
        if($payMoney == 0)
        {
            foreach($incomeMember as $uId)
            {
                $orderLog = [
                    'chapter_order_id'  => $orderId,
                    'user_id'           => $uId,
                    'check_result'      => 1,
                    'check_msg'         => "",
                    'add_time'          => $orderAddTime
                ];
                DB::table('chapter_order_log')->insert($orderLog);
            }
        }

        //==========以下为发送模板信息=============
        $this->send_notice_and_add_income($orderId);
        return apiData()->send(2001,'ok');
        return $this->apiData->set_data('order',$orderData)->send(200,'添加成功');
    }



    /**
     * 1.找到订单所属分会
     * 2.发送提醒
     * 3.添加收入记录
     * 通过查找订单，获取到订单分配的区域
     * */
    public function send_notice_and_add_income($orderId)
    {

        $memberModel    = new MemberModel();
        $chapterModel   = new ChapterModel();
        $drpModel       = new DrpModel();

        $orderInfo      = $chapterModel->get_order_info($orderId);
        $city           = $orderInfo->city;
        $cloUserId      = $orderInfo->user_id;


        //1）找到学习官所属的区域 首先检查本区域是否有会长

        $prisidentInfo  = $chapterModel->get_customer_chapter($city,$cloUserId);
        if($prisidentInfo == false)
        {
            return $this->apiData->send(4005,'没有找到扣款的分会,请联系客服');
        }


        $checkUserId    = $prisidentInfo->user_id;                  //审核人的用户ID



        //******4.找到相关受益人 这些受益人应该是新会员的三个学习官用户ID******

        $parentsDrp     = $drpModel->get_parent_drp_list($cloUserId,1);
        $parentsDrpNum  = count($parentsDrp);


        $payMoney       = $orderInfo->pay_money;   //学习官实际应该支付金额

        //========================================
        //==========以下为发送模板信息=============
        //========================================

        $surplusDiscount        = 100;
        $incomeMembers          = [];

        //把会长的放入受益人中
        if($payMoney > 0)
        {
            //向学习官的助理发送消息
            $prisidentCloInfo   = $chapterModel->get_chapter_officer_info($checkUserId);
            $assistantId        = $prisidentCloInfo->assistant;
            if($assistantId > 0)
            {
                $assistantInfo  = $memberModel->get_member_info_by_id($assistantId);
                $assistantOpenId= $assistantInfo->WeiXID ?? "";
            }else{
                $assistantOpenId = "";
            }

            $incomeInfo     = [
                'memberNumber'  => $prisidentInfo->MemNumber,
                'scale'         => $this->prisidentPercent,
                'openId'        => $prisidentInfo->WeiXID ?? "",
                'assistantId'   => $assistantOpenId
            ];

            array_push($incomeMembers,$incomeInfo);
            $surplusDiscount    = $surplusDiscount - $this->prisidentPercent;

        }


        //给自己推送一条信息

        $cloDetailInfo      = $memberModel->get_member_info_by_id($cloUserId);
        $incomeInfo = [
            'memberNumber'  => $cloDetailInfo->MemNumber,
            'scale'         => 30,
            'openId'        => $cloDetailInfo->WeiXID ?? "",
            'assistantId'   => ''
        ];
        array_push($incomeMembers,$incomeInfo);
        $surplusDiscount    = $surplusDiscount - 30;



        //=========向上两级学习官报告=====

        //1.直接学习官 推送信息

        if($parentsDrpNum > 0 & $payMoney > 0)
        {
            $parent1         = $parentsDrp[0];
            $incomeInfo = [
                'memberNumber'  => $parent1->MemNumber,
                'scale'         => 10,
                'openId'        => $parent1->WeiXID ?? "",
                'assistantId'   => ''
            ];
            array_push($incomeMembers,$incomeInfo);
            $surplusDiscount    = $surplusDiscount - 10;
        }


        //2.间接学习官推送信息
        if($parentsDrpNum > 1 && $payMoney > 0)
        {
            $parent2            = $parentsDrp[1];
            $incomeInfo         = [
                'memberNumber'      => $parent2->MemNumber,
                'scale'             => 5,
                'openId'            => $parent2->WeiXID ?? '',
                'assistantId'   => ''
            ];
            array_push($incomeMembers,$incomeInfo);
            $surplusDiscount    = $surplusDiscount - 5;
        }


        if($surplusDiscount > 0 && $payMoney > 0) //把多余的钱交给总部的小秘书  不管是公司内部提交还是外部提交
        {
            $secretaryInfo      = $memberModel->get_member_info_by_id(system_log('mishuId'));
            $incomeInfo         = [
                'memberNumber'  => $secretaryInfo->MemNumber,
                'scale'         => $surplusDiscount,
                'openId'        => $secretaryInfo->WeiXID ?? "",
                'assistantId'   => ''
            ];
            array_push($incomeMembers,$incomeInfo);
        }


        $orderTypes = [
            'member'    => '个人会员',
            'clo'       => '学习官',
            'company'   => '企业会员'
        ];

        $noticeOrderInfo  = $cloDetailInfo->YourName."提交了一个".$orderTypes[$orderInfo->order_type]."，总计金额：".$orderInfo->total_money;

        $weixinService          = new WeixinService();
        $template               = new NewOrderTemplateModel();
        $template->url          = env('ADMIN_HOST')."/clo/system/wxlogin";
        $template->orderName    = "学习官报单提示";
        $template->orderTime    = $orderInfo->add_time;
        $template->orderSn      = $orderId;
        $template->orderInfo    = $noticeOrderInfo;


        foreach($incomeMembers as $income)
        {
            $incomeMoney            = $payMoney * ($income['scale'] / 100);
            $template->openId       = $income['openId'];
            $template->otherInfo    = "本单向分会支付".$payMoney.",分享获得".$incomeMoney;

            if($incomeInfo['openId'])
            {
                $weixinService->send_chapter_order_template($template);
            }

            //给助理发送
            $template->openId   = $incomeInfo['assistantId'];
            if($incomeInfo['assistantId'])
            {
                $weixinService->send_chapter_order_template($template);
            }
            $note  = $cloDetailInfo->YourName."开发". $orderTypes[$orderInfo->order_type] ."分享". $income['scale'] . "%";
            DrpModel::income_money_log($income['memberNumber'],$cloDetailInfo->MemNumber,$orderId,$this->orderType,$payMoney,$income['scale'],$note);

        }


        //4.给客服发送短信
        $services = DB::table('system_log')
            ->where('key','like','service-%')
            ->where('key','<>','service-3')
            ->get();

        foreach($services as $service)
        {
            $template->openId   = $service->value;
            $template->url      = "http://wx.laohoulundao.com/admin_system";
            $template->orderInfo= $noticeOrderInfo;
            $template->otherInfo= "请及时确认";
            $weixinService->send_chapter_order_template($template);
        }
    }



    /**
     * 升级公司套餐
     * */
    public function upgrade_company(Request $request)
    {

        $userId         = $request->input('userId');
        $companyId      = $request->input('companyId');
        $newPackageId   = $request->input('packageId');


        $chapterModel   = new ChapterModel();
        $drpModel       = new DrpModel();
        $companyModel   = new CompanyModel();


        //***********1.检查提交的数据是否符合要求****************

        $companyInfo    = $companyModel->get_company_info($companyId);



        //*************3.找到本订单对应的发起人或会长*******************
        $userCity           = $companyInfo->city;
        $prisidentInfo      = $chapterModel->get_customer_chapter($userCity,$userId);


        if($prisidentInfo == false)
        {
            return $this->apiData->send(4005,'没有找到扣款的分会,请联系客服');
        }



        $chapterId      = $prisidentInfo->chapter_id;           //订单所属分会
        $checkUserId    = $prisidentInfo->user_id;              //审核人的用户ID
        $cloInfo        = $chapterModel->get_chapter_officer_info($userId);


        //******4.找到相关受益人 这些受益人应该是新会员的三个学习官用户ID******
        $incomeMember   = [$userId];
        $parentsDrp     = $drpModel->get_parent_drp_list($userId,1);


        foreach($parentsDrp as $parent)
        {
            array_push($incomeMember,$parent->UserID);
        }
        $incomeMember = implode(',',$incomeMember);


        //无论是学习官还是会长发起的订单 首先从已有的余额中扣除 判断余额是否足够
        //1、足够，则不需要向上级返点
        //2、不够，需要向会长请求剩余的金额并返点
        //之前的公司并不一定存在

        $newPackageInfo     = $companyModel->get_company_package_info($newPackageId);
        $totalMoney         = $newPackageInfo->money;   //总金额
        $cloSurplusMoney    = $cloInfo->surplus_money;


        //*****************5.计算需要的金额***************************
        $oldPackageMoney        = $companyModel->get_company_upgrade_discount($companyId,current_date());
        $payMoney               = $totalMoney - $oldPackageMoney;   //减去以前的套餐抵扣的金额

        if($cloSurplusMoney >= $payMoney)
        {
            $payMoney       = 0;
            $usedCloMoney   = $payMoney;    //使用的学习官的金额

        } else {

            $payMoney       = $payMoney - $cloSurplusMoney;
            $usedCloMoney   = $cloSurplusMoney;
        }

        $orderAddTime   = date_time();
        $orderData = [
            'chapter_id'        => $chapterId,
            'user_id'           => $userId,
            'order_type'        => "company",
            'check_user_id'     => $checkUserId,
            'new_member_mobile' => '',
            'new_member_name'   => '',
            'new_company_name'  => $companyInfo->company_name,
            'new_company_code'  => '',
            'company_package_id'=> $newPackageId,
            'total_money'       => $newPackageInfo->money,
            'pay_money'         => $payMoney,
            'city'              => $userCity,
            'add_time'          => $orderAddTime,
            'income_member'     => $incomeMember,
            'check_status'      => 0,
            'is_upgrade'        => 1,
            'content_id'        => $companyId
        ];


        //加入新订单
        $orderId    = DB::table('chapter_order')->insertGetId($orderData);
        $chapterModel->use_officer_money($userId,$usedCloMoney); //2 学习官

        //如果支付的金额=0 则为上级学习官自动确定订单

        //查找获益人  并记录到需要确认的表格
        if($payMoney == 0)
        {
            //0.自己
            $checkUsers     = [$userId];
            //1.上级学习官
            foreach($parentsDrp as $pDrp)
            {
                array_push($checkUsers,$pDrp->UserID);
            }
            //2.会长
            array_push($checkUsers,$checkUserId);

            //3.小秘书
            if(count($parentsDrp) == 0)
            {
                $msUserId   = system_log('mishuId');
                array_push($checkUsers,$msUserId);
            }

            foreach($checkUsers as $uId)
            {
                $orderLog = [
                    'chapter_order_id'  => $orderId,
                    'user_id'           => $uId,
                    'check_result'      => 1,
                    'check_msg'         => "",
                    'add_time'          => $orderAddTime
                ];
                DB::table('chapter_order_log')->insert($orderLog);
            }
        }


        //========================================
        //==========以下为发送模板信息=============
        //========================================
        $this->send_notice_and_add_income($orderId);

        return $this->apiData->set_data('order',$orderData)->send(200,'添加成功');
    }


    /**
     * 分会订单
     *
     * */
    public function get_orders(Request $request){

        $chapterId      = $request->input('chapterId');
        $userId         = $request->input('userId');
        $orderStatus    = $request->input('orderStatus',-1);
        $keywords       = $request->input('keywords',"");
        $roleType       = $request->input('roleType');

        //发起人查看所有订单
        $chapterModel   = new ChapterModel();
        if($roleType == 'clo')
        {
            $chapterOrders  = $chapterModel->get_chapter_orders(0,$userId,$orderStatus,$keywords);
        }
        else
        {
            $chapterOrders  = $chapterModel->get_chapter_orders($chapterId,0,$orderStatus,$keywords);
        }

        foreach($chapterOrders as $order)
        {
            $order->add_time = substr($order->add_time,5,11);
        }
        return $this->apiData->set_data('orders',$chapterOrders)->send(200,'ok');
    }



    /**
     *获取订单信息
     * */
    public function get_order_info(Request $request){
        $orderId        = $request->input('orderId');
        $chapterModel   = new ChapterModel();
        $orderInfo      = $chapterModel->get_order_info($orderId);
        $mishuId        = system_log('mishuId');

        //找到几个级别的工作状态 分别充记录表里面查找

        $incomeMember   = $orderInfo->income_member;
        $pattern        = "/,{$mishuId}$/";
        $incomeMember   = preg_replace($pattern,"",$incomeMember);

        $incomeMembers  = explode(',',$incomeMember);

        $drpModel       = new DrpModel();

        //1.会长是否处理
        $memberInfo = $drpModel->get_member_info_by_id($orderInfo->check_user_id);
        $handInfo   = $chapterModel->get_order_check_info($orderId,$orderInfo->check_user_id);
        $prisidentHandInfo          = $handInfo ? $handInfo : new \stdClass();
        $prisidentHandInfo->isHand  = $handInfo ? 1 : 0;
        $prisidentHandInfo->YourName= $memberInfo->YourName;
        $prisidentHandInfo->percent = $this->prisidentPercent;

        //第一学习官是否处理
        $memberInfo     = $drpModel->get_member_info_by_id($orderInfo->user_id);
        $handInfo       = $chapterModel->get_order_check_info($orderId,$orderInfo->user_id);
        $drpHandInfo    = $handInfo ? $handInfo : new \stdClass();
        $drpHandInfo->isHand    = $handInfo ? 1 : 0;
        $drpHandInfo->YourName  = $memberInfo->YourName;
        $drpHandInfo->percent   = 30;

        $mishuHandInfo  = false;

        //第二学习官是否处理
        $parentClo              = $drpModel->get_parent_drp_list($orderInfo->user_id);
        if(count($parentClo) > 0)
        {
            $userId     = $parentClo[0]->UserID;
            $memberInfo = $drpModel->get_member_info_by_id($userId);
            $handInfo   = $chapterModel->get_order_check_info($orderId,$userId);
            $parentDrpHandInfo          = $handInfo ? $handInfo : new \stdClass();
            $parentDrpHandInfo->isHand  = $handInfo ? 1 : 0;
            $parentDrpHandInfo->YourName= $memberInfo->YourName;
            $parentDrpHandInfo->percent = 10;

        } else { //如果没有第二学习官，就有小秘书

            $handInfo       = $chapterModel->get_order_check_info($orderId,$mishuId);
            if($handInfo)
            {
                $mishuHandInfo          = $handInfo;
                $mishuHandInfo->isHand  = 1;

            } else {

                $mishuHandInfo  = new \stdClass();
                $mishuHandInfo->isHand  = 0;
                $mishuHandInfo->YourName = "";

            }
            $mishuHandInfo->percent  = 10;
        }

        //第三学习官是否处理
        $topDrpHandInfo = false;

        $handInfo = [
            'prisidentHandInfo' => $prisidentHandInfo,
            'drpHandInfo'       => $drpHandInfo,
            'parentDrpHandInfo' => $parentDrpHandInfo,
            'topDrpHandInfo'    => $topDrpHandInfo,
            'mishuHandInfo'     => $mishuHandInfo
        ];

        return $this->apiData
            ->set_data('orderInfo',$orderInfo)
            ->set_data('handInfo',$handInfo)
            ->send(200,'ok');
    }




    /**
     * 用户处理订单
     * 每一个涉及到本订单的用户都需要进行确认 但是确认需要区分是否收到返点
     * 1.父级学习官收到返点 所有拥有返点的人员确认后，总部进行确认
     * 2.如果不需要向父级学习官确认，则会长确认后总部即可进行确认
     * */
    public function hand_order(Request $request){

        $type           = $request->input('type');    //用户的角色
        $userId         = $request->input('userId');
        $orderId        = $request->input('orderId');
        $assistant      = $request->input('assistant');

        $chapterModel   = new ChapterModel();
        $drpModel       = new DrpModel();
        $orderInfo      = $chapterModel->get_order_info($orderId);
        $memberInfo     = $drpModel->get_member_info_by_id($userId);
        $userRole       = "";

        //判断提交者能否确认订单
        switch($type){
            case 'prisident':
                $userRole   = "会长";
                if($userId != $orderInfo->check_user_id){
                    return $this->apiData->send(4001,"您无权确认");
                }
                break;
            case 'drp':
                $userRole   = "学习官";
                if($userId != $orderInfo->user_id){
                    return $this->apiData->send(4002,'您不是学习官');
                }
                break;
            case 'parentDrp':
                $userRole   = "学习官";
                $parentsDrp = $drpModel->get_parent_drp_list($orderInfo->user_id,1);
                if(count($parentsDrp) == 1){
                    $parentsDrp = $parentsDrp[0];
                    if($userId != $parentsDrp->UserID){
                        return $this->apiData->send(4003,'您无权操作');
                    }
                }else{
                    return $this->apiData->send(4003,'非法操作');
                }
                break;
            case 'topDrp':
                $userRole   = "学习官";
                $parentsDrp = $drpModel->get_parent_drp_list($orderInfo->user_id,2);
                if(count($parentsDrp) == 2){
                    $parentsDrp = $parentsDrp[1];
                    if($userId != $parentsDrp->UserID){
                        return $this->apiData->send(4003,'您无权操作');
                    }
                }else{
                    return $this->apiData->send(4003,'非法操作');
                }
                break;
            case 'mishu':
                $userRole   = "小秘书";
                $mishuId    = system_log('mishuId');
                if($userId != $mishuId)
                {
                    return $this->apiData->send(4005,"您无权操作");
                }
        }

        $memberTypes = [
            "prisident" => "会长",
            "clo"       => "学习官",
            "company"   => "企业会员",
            "member"    => "个人会员"
        ];

        if($orderInfo->order_type == 'company'){
            $newUser = $orderInfo->new_company_name;
        }else{
            $newUser = $orderInfo->new_member_name;
        }


        $orderOwnerInfo     = $drpModel->get_member_info_by_id($orderInfo->user_id);
        $template           = new ChangeOrderTemplateModel();

        //给下订单的人发送 微信提示
        $msg    = "您在{$orderInfo->add_time}提交的订单【{$newUser}】【{$memberTypes[$orderInfo->order_type]}】已被确认。";

        $template->url          = env('ADMIN_HOST')."/clo/system/wxlogin";
        $template->title        = "订单确认提示";
        $template->orderSn      = $orderInfo->chapter_order_id;
        $template->changeInfo   = "{$userRole}{$memberInfo->YourName}对本订单进行了确认!";
        $template->orderInfo    = $msg;
        $template->otherInfo    = "点击查看详情";
        $template->openId       = $orderOwnerInfo->WeiXID;
        $weixinService          = new WeixinService();
        if($orderOwnerInfo->WeiXID)
        {
            $weixinService->send_chapter_order_change_template($template);
        }

        $data = [
            'chapter_order_id'  => $orderId,
            'user_id'           => $userId,
            'check_result'      => 1,
            'check_msg'         => "处理人：" . $assistant ? "助理" : "本人",
            'add_time'          => date_time()
        ];
        DB::table('chapter_order_log')->insert($data);

        //检查所有用户(受益人和会长)的确认状态 如果所有用户确认了，则给客服发送信息
        $users  = $orderInfo->income_member;
        $users  = explode(',',$users);
        array_push($users,$orderInfo->check_user_id);
        $users  = array_unique($users);
        $total  = DB::table('chapter_order_log')
            ->where('chapter_order_id',$orderId)
            ->where('is_delete',0)
            ->whereIn('user_id',$users)
            ->groupBy('chapter_order_id','user_id')
            ->get();

        if(count($total) == count($users)) //所有人已审核
        {
            //4.给客服发送短信
            $services = DB::table('system_log')
                ->where('key','like','service-%')
                ->where('key','<>','service-3')
                ->get();

            foreach($services as $service)
            {
                $smg  = "学习官{$orderOwnerInfo->YourName}开发的新{$userRole}已确认完毕";
                $template->title    = "订单审核完毕";
                $template->openId   = $service->value;
                $template->url      = "http://wx.laohoulundao.com/admin_system";
                $template->orderSn  = $orderInfo->chapter_order_id;
                $template->orderInfo= $smg;
                $template->changeInfo= "所有学习官已对本订单进行了确认!";
                $template->otherInfo = "前往审核";
                $weixinService->send_chapter_order_change_template($template);
            }
        }
        return $this->apiData->send(200,'ok');
    }




}

